package com.example.utils;


import com.example.app.AppUtils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * @Classname FileWatcher
 * @Description TODO
 * @Date 2022/6/5 19:58
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class FileWatcher {

  //目录监听
  public static void init(){
     listener();
  }

  public static void listener(){


    // 轮询间隔 5 秒
    long interval = TimeUnit.SECONDS.toMillis(1);
    //不使用过滤器,使用过滤器时创建FileAlterationObserver对象时传入第二个参数FileFilter
    String path= PathUtils.getPath();
    //加载jar包
    loadFile(path);
    FileAlterationObserver observer = new FileAlterationObserver(new File(path));
    FileListener fileListener = new FileListener();
    observer.addListener(fileListener);
    //创建文件变化监听器
    FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
    // 开始监控
    try {
      monitor.start();
    }catch (Exception e){}

  }



  public static void loadFile(String path){
      if(path.contains("ui-source")|| path.contains("start-ui")){
          return;
      }
      File file = new File(path);
      File[] files=file.listFiles();
      for (int i = 0; i < files.length ; i++) {
          File f = files[i];
          if(f.isDirectory()){

              if(f.getPath().contains("ui-source")|| f.getPath().contains("start-ui")){
                    continue;
              }
              loadFile(f.getPath());
          }else {
              if(f.getName().endsWith("fat.jar") && !f.getName().startsWith("start-system")
                    && !f.getName().startsWith("start-base")){

                  ClazzScanUtils.onload(f.getPath(),f.getName());
              }
          }
      }
  }



}
